import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, Button, message, DatePicker, Tag, Modal, Row, Col, InputNumber, Checkbox } from "antd";
import { SearchOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack'
import { apiGetUnuseCouponGoodsAdd, apiGetUnuseCouponGoodsPage, apiGetUnuseCouponGoodsDel, apiGetUnuseCouponGoodsView, apiGetUnuseCouponGoodsEdit } from '@/request/coupons'
import { apiGetGoodsList, apiAdd, apiEdit, apiGetGoodsDetail, apiView } from '@/request/marketingTool'
import './style.scss'
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"

const { Option } = Select
const { TextArea } = Input

export default class UnuseCoupons extends Component {
    constructor() {
        super()
        this.FormRef = React.createRef()
        this.addFormRef = React.createRef()
        this.state = {
            columns: [
                {
                    title: "商品名称",
                    dataIndex: "goodsName",
                    key: "goodsName",

                },
                {
                    title: "规格",
                    dataIndex: "sku",
                    key: "sku",

                },
                {
                    title: "失效类型",
                    dataIndex: "unUseTypes",
                    key: "unUseTypes",
                    render: (text, render, index) => {
                        let unUseTypes = []
                      
                       
                        if(render.couponStatus==1){
                            unUseTypes.push('不使用优惠券')
                        }
                         if(render.fullDiscountStatus==1){
                            unUseTypes.push('不参与全平台满减')
                        }
                        return <div>
                            {unUseTypes.join('&')}
                        </div>
                    }
                },
                {
                    title: "操作时间",
                    dataIndex: "createTime",
                    key: "createTime",

                }, {
                    title: "操作",
                    render: (text, render, index) => {
                        return <div>
                            <TheButton haspermi={["unusecoupons:index:edit"]} onClick={() => this.edit(render)}>编辑</TheButton>
                            <TheButton haspermi={["unusecoupons:index:del"]} onClick={() => this.del(render.id)}>删除</TheButton>
                        </div>
                    }
                },
            ],
            options: [
                {
                    label: '不使用优惠券',
                    value: 'unCoupon',
                }, 
                // {
                //     label: '不参与全平台满减',
                //     value: 'unFullSubtraction',
                // }
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: 0,
            isModalVisible: false,
            title: '新增',
            editId: '',
            loading: false,
            goodsList: [],
            productSku: {},
            currentSku: {},
            newColumns: [],
            form_show: true,
            searchOption: [
                { field: 'goodsName', label: '商品名称', placeholder: '商品名称', required: false, rules: [], type: 'Input', defaultValue: '' },
                {
                    field: 'unUseTypes', label: '失效类型', placeholder: '请选择失效类型', required: false, rules: [], type: 'Select', options: [
                        {
                            label: '不使用优惠券',
                            value: 'unCoupon'
                        }, {
                            label: '不参与全平台满减',
                            value: 'unFullSubtraction',
                        }, {
                            label: '不使用优惠券&不参与全平台满减',
                            value: 'unFullSubtraction&unCoupon',
                        }
                    ], defaultValue: ''
                },

            ],
            queryForm: {},

        }
    }
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        this.getData()
        this.getGoodsList()
    }
    async getData(values) {
        let { pageNo, pageSize } = this.state.pageData
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            let res = await apiGetUnuseCouponGoodsPage({ pageNo, pageSize, ...this.state.queryForm })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount

                })
            }
        })


    }
    selectFilter(input, option) {
        return option.children.toLowerCase().includes(input.toLowerCase())
    }
    async getGoodsList(libraryId) {
        let res = await apiGetGoodsList()
        if (res.code === 0) {
            this.setState({
                goodsList: res.data,
            })
        }
    }
    goodsChange(e, row) {
        this.apiGetGoodsDetail(e)
    }
    async apiGetGoodsDetail(goodsId, skuId) {
        let res = await apiGetGoodsDetail({ goodsId })
        if (res.code === 0) {
            if (skuId) {
                this.setState({
                    productSku: res.data,
                    currentSku: res.data.skuInfo.filter(item => item.SKUId === skuId)[0]
                })
            } else {
                this.setState({
                    productSku: res.data,
                    currentSku: res.data.skuInfo[0]
                })
            }

        }
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    triggerSkuTag(row) {
        if(this.state.title ==='编辑')return
        this.setState({
            currentSku: row
        })
    }
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    onTableRefresh() {
        this.getData()
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    onFormSearch(values) {
        if(values.unUseTypes==='unCoupon'){
            values.couponStatus = 1
        }
        if(values.unUseTypes==='unFullSubtraction'){
            values.fullDiscountStatus = 1
        }
        if(values.unUseTypes==='unFullSubtraction&unCoupon'){
            values.fullDiscountStatus = 1
            values.couponStatus = 1
        }
        delete values.unUseTypes

        this.setState({
            pageData: { pageNo: 1, pageSize: 10 }
        }, () => {
            this.getData(values)
        })
    }
    reset() {
        if(this.state.title =='编辑'){
            this.addFormRef.current.setFieldsValue({
                unUseTypes: []
            })
        }else{
            this.addFormRef.current.setFieldsValue({
                goodsId: '',
                unUseTypes: []
            })
            this.setState({
                productSku: {},
                currentSku: {}
            })
        }
       
    }
    async edit(row) {
        this.apiGetGoodsDetail(row.goodsId, row.goodsSkuId)
        this.setState({
            isModalVisible: true,
            title: '编辑',
            editId: row.id
        }, () => {
            let unUseTypes = []
            if (row.couponStatus == 1) unUseTypes.push('unCoupon')
            if (row.fullDiscountStatus) unUseTypes.push('unFullSubtraction')
            this.addFormRef.current.setFieldsValue({
                goodsId: row.goodsId,
                unUseTypes
            })
        })

    }
    async del(id) {
        React.$confirm({
            title: `您确定删除该条数据吗？`,
            onOk: async () => {
                let res = await apiGetUnuseCouponGoodsDel({ id })
                if (res.code === 0) {
                    this.pageChange(1, 10)
                }
            }
        })


    }
    add() {
        this.setState({
            isModalVisible: true,
            title: '新增',
            editId: ''
        }, () => {
            this.reset()
        })
    }

    cancel = () => {
        this.reset()
        this.setState({ isModalVisible: false, editId: '' })
    }
    async onFinish(values) {
        if (this.state.editId) {
            let res = await apiGetUnuseCouponGoodsEdit({
                goodsId: this.state.productSku.goodsInfo.goodsId,
                goodsSkuId: this.state.currentSku.goodsSkuId,
                couponStatus: values.unUseTypes.includes('unCoupon') ? 1 : 0,
                fullDiscountStatus: values.unUseTypes.includes('unFullSubtraction') ? 1 : 0,
                id: this.state.editId
            })
            if (res.code === 0) {
                this.reset()
                this.setState({
                    isModalVisible: false,
                    editId: ''
                })
                this.getData()
            }
        } else {
            let res = await apiGetUnuseCouponGoodsAdd({
                goodsId: this.state.productSku.goodsInfo.goodsId,
                goodsSkuId: this.state.currentSku.goodsSkuId,
                couponStatus: values.unUseTypes.includes('unCoupon') ? 1 : 0,
                fullDiscountStatus: values.unUseTypes.includes('unFullSubtraction') ? 1 : 0
            })
            if (res.code === 0) {
                this.reset()
                this.setState({
                    isModalVisible: false
                })
                this.getData()
            }
        }

    }
    render() {
        let { columns, goodsList, status, title, options, productSku, currentSku, dataSource, pageData, total, isModalVisible, loading, form_show, newColumns, searchOption } = this.state
        return (
            <div className="p-layout-box">
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                    onGetValues={(values) => this.onFormSearch(values)}
                    onReset={(values) => this.onReset(values)}
                >
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.onTableRefresh()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton haspermi={["unusecoupons:index:add"]} size="middle" onClick={() => this.add()} type="primary">新增</TheButton>

                </TheTableExtend>
                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={newColumns}
                    dataSource={dataSource}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />

                <Modal title={title} visible={isModalVisible} width="40%"
                    onCancel={() => this.cancel()}
                    footer={null}
                >
                    <Form
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        ref={this.addFormRef}
                        onFinish={(values) => this.onFinish(values)}
                    >

                        <Col span={24}>
                            <Form.Item
                                label="选择商品"
                                name="goodsId"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择商品!',
                                    },
                                ]}
                            >
                                <Select
                                    showSearch
                                    disabled={title=='编辑'}
                                    optionFilterProp="children"
                                    filterOption={(input, option) => this.selectFilter(input, option)}
                                    style={{
                                        width: '100%',
                                    }}
                                    onChange={(e, obj) => this.goodsChange(e, obj)}
                                    placeholder="请选择商品"
                                >
                                    {
                                        goodsList.map(item => <Option option={item} key={item.goodsId} value={item.goodsId}>{item.goodsName}</Option>)
                                    }
                                </Select>

                            </Form.Item >
                        </Col>

                        <Col>
                            {
                                productSku.hasOwnProperty('goodsInfo') ?
                                    <Form.Item
                                        wrapperCol={{
                                            offset: 4,
                                            span: 16,
                                        }}
                                    >
                                        <div className='goodsDesc'>
                                            <div className='info'>
                                                <img src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''} alt="商品图片" className='goodsImg' />
                                                <div className="goodsInfo">
                                                    <div className='name'>{productSku.goodsInfo.goodsName}</div>
                                                    {/* <div className='stock' >
                                                            可售库存：{currentSku.stock}
                                                        </div>
                                                        <div className='stock' >
                                                            待出库存：{currentSku.waiteOutCount}
                                                        </div>
                                                        <div className='stock' >
                                                            实际库存：{currentSku.realStock}
                                                        </div> */}
                                                </div>
                                            </div>
                                            <div className='goodsSku'>
                                                {
                                                    productSku.skuInfo.map(item =>
                                                        <Tag className='tag' key={item.SKUId} color={item.SKUId === currentSku.SKUId ? "cyan" : ''} onClick={() => this.triggerSkuTag(item)}>
                                                            {item.skuAttribute.map(item2 => item2.value).join(',')}
                                                        </Tag>
                                                    )
                                                }

                                            </div>
                                        </div>
                                    </Form.Item> : null
                            }
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="失效类型"
                                name="unUseTypes"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择失效类型!',
                                    },
                                ]}
                            >
                                <Checkbox.Group options={options} />
                            </Form.Item >
                        </Col>
                        <Col>
                            <Form.Item wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}>
                                <Space size="small" style={{ marginLeft: 10 }}>

                                    <Button type="default" onClick={() => this.reset()}>
                                        重置
                                    </Button>
                                    <Button type="primary" htmlType="submit">
                                        确定
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Col>

                    </Form>
                </Modal>
            </div>
        );
    }
}
